package cn.itsource.service.impl;

import cn.itsource.domain.User;
import cn.itsource.exception.NoAccountException;
import cn.itsource.exception.PasswordComparisonException;
import cn.itsource.mapper.UserMapper;
import cn.itsource.service.IUserService;
import cn.itsource.util.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;



    @Override
    public String login(String username, String password) {
        if(StringUtils.isBlank(username)){
            throw new RuntimeException("用户名必填!!");
        }
        if(StringUtils.isBlank(password)){
            throw new RuntimeException("密码必填!!");
        }
        //根据用户名在数据库中去查询用户对象
        User user = userMapper.getUserByUsername(username);
        if (user == null) {
            throw new NoAccountException("用户名不存在!");
        }
        //密码比对
        if(!password.equals(user.getPassword())){
            throw new PasswordComparisonException("密码错误!");
        }
        //随机产生token
        String token = UUID.randomUUID().toString();
        //把查询到的用户对象，放到map集合中(key:token  value:用户对象)   把我们登录对象放到map集合中
        UserContext.setLoginUser(token, user);
        //返回token
        return token;
    }

    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid.toString());
    }


}
